<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>树形菜单</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
    <style>
        .tree-menu {
            display: none;
        }

        .tree-menu.top-level {
            display: block;
        }

        .tree-menu li {
            position: relative;
            font-size: 16px;
            padding-left: 16px;
            line-height: 32px;
        }

        .tree-menu .toggle-icon {
            position: absolute;
            left: 0;
            top: 10px;
            width: 12px;
            height: 12px;
            font-size: 12px;
            line-height: 12px;
            text-align: center;
            border: 1px solid #AAA;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <ul class="tree-menu top-level" id="treeMenu"></ul>
    <script>
        //获取ID为'treeMenu'的元素
        const treeMenu = document.getElementById("treeMenu");
        //为该元素添加一个点击事件监听器
        treeMenu.onclick = function (e) {
            //获取点击的目标元素和它的下一个兄弟元素
            let target = e.target;
            let submenu = target.nextElementSibling;
            //如果点击的目标元素有'toggle-icon'类，并且存在下一个兄弟元素，则切换目标元素的'open'类，并切换下一个兄弟元素的显示状        态
            if (target.classList.contains("toggle-icon") && submenu) {
                target.classList.toggle("open");
                submenu.style.display = submenu.style.display === "block" ? "none" : "block";
            }
        };
        //定义一个函数，根据数据渲染树形菜单的HTML
        function renderTree(data) {
            let html = "";
            data.forEach(item => {
                let { name, children, open } = item;
                html += `
                    <li>
                        <span>${name}</span>
                        ${children ? `<em class="toggle-icon${open ? ' open' : ''}">${open ? '-' : '+'}</em>` : ``}
                        ${children ?
                        `<ul class="tree-menu" style="display: ${open ? 'block' : 'none'};">
                            ${renderTree(children)}
                        </ul>`: ``
                    }
                    </li>`;
            });
            return html;
        }
        let xhr = new XMLHttpRequest();
        xhr.open("get", "https://static.zhufengpeixun.com/data_1684067863819.json");
        xhr.onreadystatechange = function () {
            //当请求成功完成时，解析响应数据并调用resolve函数
            if (xhr.readyState === 4 && xhr.status === 200) {
                let data = JSON.parse(xhr.response);
                let treeHTML = renderTree(data);
                treeMenu.innerHTML = treeHTML;
            }
        };
        xhr.send();
    </script>
</body>
</html>